#import "MO2XMLEntitiesImporter.h"


@implementation MO2XMLEntitiesImporter

- (id)initWithContentsOfFile:(NSString *)aPath {
	self = [super init];
	if(self) {
		[self setPath:aPath];
		[self setProperties:nil];
	}
	return self;
}

- (void)dealloc {
	[path release];
	[properties release];
	
	[super dealloc];
}

- (void)setPath:(NSString *)value {
	[value retain];
	[path release];
	path = value;
}

- (NSString *)path {
	return path;
}

- (BOOL)importEntities {
	NSArray *dictionaries = [self entitiesAsDictionaries];
	NSEnumerator *dictionariesEnumerator = [dictionaries objectEnumerator];
	id entity;	// represents a entity
	while(entity = [dictionariesEnumerator nextObject]) {
		NSString *entityName = [entity valueForKey:@"name"];
		NSArray *entityData = [entity valueForKey:@"data"];
		NSEnumerator *entityDataEnumerator = [entityData objectEnumerator];
		id managedObjectAsDictionary;
		while(managedObjectAsDictionary = [entityDataEnumerator nextObject]) {
			NSEntityDescription *entityDescription = [NSEntityDescription entityForName:entityName inManagedObjectContext:[self managedObjectContext]];
			Class classObject = NSClassFromString([entityDescription managedObjectClassName]);
			
			NSManagedObject *mo = [[classObject alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:[self managedObjectContext]];
			
			NSArray *managedObjectKeys = [managedObjectAsDictionary allKeys];
			NSEnumerator *managedObjectKeysEnumerator = [managedObjectKeys objectEnumerator];
			id key;
			while(key = [managedObjectKeysEnumerator nextObject]) {
				id value = [managedObjectAsDictionary objectForKey:key];
				
				[mo setValue:value forKey:key];
			}
			
			NSDictionary *propertiesForAll = [self properties];
			NSArray *relationshipsKeys = [propertiesForAll allKeys];
			NSEnumerator *relationshipsKeysEnumerator = [relationshipsKeys objectEnumerator];
			id relationshipKey;
			while(relationshipKey = [relationshipsKeysEnumerator nextObject]) {
				id value = [propertiesForAll valueForKey:relationshipKey];
				[mo setValue:value forKey:key];
			}

		}
	}
	return YES;
}

- (NSArray *)entitiesAsDictionaries {
	return [NSArray arrayWithContentsOfFile:[self path]];
}

- (NSDictionary *)properties {
	return properties;
}

- (void)setProperties:(NSDictionary *)value {
	[value retain];
	[properties release];
	properties = value;
}

@end
